#!/bin/bash

overridesPath="/private/var/db/launchd.db/com.apple.launchd/overrides.plist";
overridesDir="/private/var/db/launchd.db/com.apple.launchd";
systemLaunchDaemonPath="/System/Library/LaunchDaemons/"
apacheLaunchDaemonPlistFile="org.apache.httpd.plist"
plistBuddy="/usr/libexec/PlistBuddy";

# Service list per 11065945
obsoleteServices=(
	com.apple.AppleVNCServer
	com.apple.DeviceManagement.SCEPHelper
	com.apple.HeadlessStartup
	com.apple.IPAliases
	com.apple.Rooms
	com.apple.afctl
	com.apple.collabauthd
	com.apple.collabcored1
	com.apple.collabcored2
	com.apple.collabcored3
	com.apple.collabcored4
	com.apple.collabd
	com.apple.collabd.expire
	com.apple.collabd.notifications
	com.apple.collabd.quicklook
	com.apple.collabfeedd
	com.apple.collabsandboxd
	com.apple.devicemanager
	com.apple.diskspacemonitor
	com.apple.emailrules
	com.apple.emailrules.nightly
	com.apple.hwmond
	com.apple.learnjunkmail
	com.apple.mail_migration
	com.apple.natd
	com.apple.passwordreset
	com.apple.pcastserverd
	com.apple.ppp.l2tp
	com.apple.ppp.pptp
	com.apple.push_notify
	com.apple.salearn
	com.apple.serialnumberd
	com.apple.servermgrd
	com.apple.swupdate.host
	com.apple.swupdate.sync
	com.apple.updatesa
	com.apple.watchdogtimerd
	com.apple.wiki_sieve_manager
	com.apple.wikid
	com.apple.wikid.logcompressor
	com.apple.wikid.mailinglists
	com.apple.wikid.quicklook
	com.apple.xftpd
	com.apple.xgridd.pcastserver
	com.apple.xserve.serial-ports
	edu.cmu.andrew.cyrus.master
	org.addressbookserver.addressbookserver
	org.apache.htcacheclean
	org.apache.tomcat
	org.calendarserver.calendarserver
	org.clamav.clamd
	org.clamav.freshclam
	org.clamav.freshclam-init
	org.dovecot.dovecotd
	org.dovecot.fts.update
	org.jabber.jabberd
	org.jabber.jabberd_notification
	org.jabber.proxy65
	org.list.mailmanctl
	org.mysql.mysqld
	org.postgresql.postgres
);

function deleteObsoleteOverrides() {
	for obsoleteService in ${obsoleteServices[@]}; do
		/bin/echo removing override for ${obsoleteService};
		${plistBuddy} -c "delete :${obsoleteService}" "${DSTROOT}/${overridesPath}" 2>/dev/null;
	done
}

# Updated per 10806436
serverExceptions=(
					org.apache.httpd
					org.net-snmp.snmpd
					);

function setDisabledKey() {
	local label="${1}";
	local disabled="${2}";
	${plistBuddy} -c "add ${label} dict" "${DSTROOT}/${overridesPath}" 2>/dev/null;
	${plistBuddy} -c "delete :${label}:Disabled" "${DSTROOT}/${overridesPath}" 2>/dev/null;
	${plistBuddy} -c "add ${label}:Disabled bool ${disabled}" "${DSTROOT}/${overridesPath}";
}

function applyCustomOverrides() {
	setDisabledKey com.apple.mDNSResponder 0;
	setDisabledKey com.apple.mDNSResponderHelper 0;
	setDisabledKey com.apple.hdiejectd 0;
}

function disableServerExceptions() {
	for exception in ${serverExceptions[@]}; do
		/bin/echo disabling ${exception};
		setDisabledKey ${exception} 1;
	done
}

isServerMigration=0;
# As of Zin, it's a server migration if the Source was a server.
if [[ -e "${SRCROOT}/System/Library/CoreServices/ServerVersion.plist" ]]; then
	isServerMigration=1;
fi

if [[ ! -d "${DSTROOT}/${overridesDir}" ]]; then
	/bin/mkdir -p "${DSTROOT}/${overridesDir}";
fi

if [[ -e "${SRCROOT}/${overridesPath}" ]]; then
	/bin/echo "Copying contents of ${SRCROOT}/private/var/db/launchd.db";
	/System/Library/PrivateFrameworks/SystemMigration.framework/Resources/safecp -f "${SRCROOT}"/private/var/db/launchd.db/* "${DSTROOT}"/private/var/db/launchd.db/;
	if [[ ${isServerMigration} == 1 ]]; then
		disableServerExceptions;
		deleteObsoleteOverrides;
	fi
	for override in "${DSTROOT}"/private/var/db/launchd.db/com.apple.launchd.peruser.*; do
		if [[ "${override}" =~ .*com.apple.launchd.peruser\.(.*) ]]; then
			chown -R "${BASH_REMATCH[1]}" "${override}";
		fi
	done
	
	applyCustomOverrides;
	
	exit;
fi

/bin/echo "Migrating launchd states to overrides.plist";
/bin/rm -f "${DSTROOT}/${overridesPath}";

for plist in "${SRCROOT}"/System/Library/LaunchDaemons/*.plist "${SRCROOT}"/System/Library/LaunchAgents/*.plist; do
	if [[ ${isServerMigration} == 1 ]]; then
		skip=0;
		for exception in ${serverExceptions[@]}; do
			if [[ ${plist} =~ ${exception} ]]; then
				/bin/echo skipping ${plist};
				skip=1;
				break;
			fi
		done
	
		if [[ ${skip} == 1 ]]; then
			continue;
		fi
	fi
	
	disabled="`${plistBuddy} -c 'print Disabled' \"${plist}\" 2>&1`";
	if [[ $? != "0" ]]; then
		disabled="0";
	fi
	
	label="`${plistBuddy} -c 'print Label' \"${plist}\" 2>&1`";

	# 9724382 & 10516428
	if [[ ${label} == "com.apple.stackshot" ]]; then
	        continue;
	fi

	if [[ $? == "0" ]]; then
		setDisabledKey ${label} ${disabled};
		/bin/chmod 600 "${DSTROOT}/${overridesPath}";
	fi
done

if [[ ${isServerMigration} == 1 ]]; then
	# Clean up override entries belonging to services which no longer exist
	deleteObsoleteOverrides;
fi

applyCustomOverrides;